package ru.urfc.portal.ui.client.googlets.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Widget;

import ru.urfc.portal.ui.client.BaseGooglet;
import ru.urfc.portal.ui.client.controllers.SimpleItemsController;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;

public class DocumentsNew extends BaseGooglet {

	interface Binder extends UiBinder<Widget, DocumentsNew> {}
	private static Binder binder = GWT.create(Binder.class);
	
	
	
	private final ValueChangeHandler<String> historyValueChangeHandler = new ValueChangeHandler<String>() {
		
		@Override
		public void onValueChange(final ValueChangeEvent<String> event) {
			final String typeCode = event.getValue();
			if (typeCode.length() != 0) {
				History.back();
				createAndShowDocument(typeCode);
			}
		}

		protected void createAndShowDocument(final String typeCode) {
			GWT.log(typeCode);
			createDocument(typeCode);
		}

		protected void createDocument(final String typeCode) {
			final GridDescriptor descriptor = new GridDescriptor(DOCUMENT, CLIENTS, getClientId(), DOCUMENTS);
			final Element div = DOM.createDiv();
			div.setInnerText(typeCode);
			descriptor.addTextField("type/code", div).setEditable();
			final SimpleItemsController controller = new SimpleItemsController(descriptor) {
				
				@Override
				public void onUpdate(Object data) {
					GWT.log("create document: " + data);
					String docId = data.toString();
					final String urlTemplate = patchHref(PAGE_DOCUMENT_DETAILS);
					final String url = urlTemplate.replace("{0}", docId).replace("{typeCode}", typeCode);
					redirect(url);
				}
			};
			controller.doPost();
		}
	};

	@Override
	protected void init() {
		initWidget(binder.createAndBindUi(this));
		patchHyperlinks(getElement());
		History.addValueChangeHandler(historyValueChangeHandler);
	}

}
